package ExecuteEngine;

import java.util.List;

import RecordManagement.*;
import SystemManagement.*;
import parse.*;
import Type.*;
import Const.*;
import java.util.*;

public class TableScan implements Operation{
	String tableName;
	RM_FileHandle fileHandle;
	RM_FileScan fileScan;
	RM_Manager rm;
	SM_Manager sm;
	List<DataAttrInfo> info = new ArrayList<DataAttrInfo>();
	RM_Record record;
	Tuple t;
	
	public TableScan(String table, RM_Manager rm, SM_Manager sm){
		this.tableName = table;
		this.rm = rm;
		this.sm = sm;
	}
	
	public void Open(){
		try{
			fileHandle = rm.OpenFile(this.tableName);
		}
		catch(java.io.IOException e){
			
		}
		
		ScanType st = new ScanType(Types.Varchar, 
				                   Constant.MAXNAME, 0, ScanType.OP_NO,
				                   null, ScanType.PIN_NORMAL);
		
		fileScan = new RM_FileScan(this.fileHandle,st);
		
		sm.GetDataAttrInfo(this.tableName, this.info);
		
		for(int i=0; i<info.size(); i++)
			t.tuple.add(new Element(this.tableName, info.get(i).attrName, null));
	}
	
	public boolean hasNext(){
		if((record = fileScan.GetNextRec()) == null)
			return false;
		
		return true;
	}
	
	public Tuple GetNext()
	{
		int position = 0;
		for(int i=0; i<info.size(); i++){
			int length = info.get(i).attrLength;
			
			byte b[] = new byte[length];
			System.arraycopy(record.data, position, b, 0, length);
			
			if(info.get(i).attrType == Types.Varchar)
				t.tuple.get(i).setValue(new VarcharItem(new StringBuffer(new String(b))));
			else
			{
				int n = (((int)b[0]) << 24) + (((int)b[1]) << 16) + (((int)b[2]) << 8) + b[3];
				t.tuple.get(i).setValue(new IntegerItem(n));
			}
			
			position += length;
		}
		
		return t;
	}
	
	public void Close(){
		fileScan.CloseScan();
		rm.CloseFile(fileHandle);
	}
}
